package com.zou.jokes.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.zou.jokes.Constant;
import com.zou.jokes.HiddenActivity;
import com.zou.jokes.R;
import com.zou.jokes.beans.JokesBean;
import com.zou.jokes.sqlite.MyDao;
import com.zou.jokes.utils.DisplayUtil;
import com.zou.jokes.utils.RxBus;
import com.zou.jokes.utils.SharedPreferencesUtils;
import com.zou.jokes.utils.ToastUtil;
import com.zou.jokes.utils.UserEvent;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zou on 2016/6/3.
 */
public class JokesAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private static final int     TIME          = 0;
    private static final int     MORE          = 1;
    private static final int     JOKES         = 2;
    private              boolean isLoadingMore = false;
    private final List<JokesBean.ResultBean.DataBean> datas;
    ClipboardManager clipboardManager;
    Context          context;
    private final MyDao myDao;

    public void setLoadingMore(boolean loadingMore) {
        isLoadingMore = loadingMore;
    }

    public JokesAdapter(List<JokesBean.ResultBean.DataBean> datas, Context context) {
        this.datas = datas;
        this.context = context;
        this.clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        myDao = new MyDao(context);

    }

    @Override

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TIME:
                return new TimeHodler(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_time, parent, false));
            case MORE:
                return new MoreHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_more, parent, false));
            case JOKES:
                return new JokesHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_jokes, parent, false));
            default:
                return null;

        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof JokesHolder) {
            ((JokesHolder) holder).btn_copy_content.setTag(position);
            ((JokesHolder) holder).btn_copy_content.setOnClickListener(this);
            ((JokesHolder) holder).btn_share_joke.setTag(position);
            ((JokesHolder) holder).btn_share_joke.setOnClickListener(this);
            ((JokesHolder) holder).btn_like_joke.setTag(position);
            ((JokesHolder) holder).btn_like_joke.setOnClickListener(this);

            String textSize = (String) SharedPreferencesUtils.getParam(context, Constant.TEXTSIZE, "20");
            ((JokesHolder) holder).joke_content.setTextSize(Float.parseFloat(textSize));
            ((JokesHolder) holder).joke_content.setText(datas.get(position - 1).getContent());

            ((JokesHolder) holder).update_time.setText(datas.get(position - 1).getUpdatetime());

/*            if (myDao.queryExists(datas.get(position - 1).getHashId())) {
                ((JokesHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
            }*/

            Observable.just(myDao.queryExists(datas.get(position - 1).getHashId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            ((JokesHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
                        } else {
                            ((JokesHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                        }
                    });
        }
    }

    @Override
    public int getItemCount() {
//        不足20条不会显示加载更多,没有条目不会显示更新时间
        if (datas.size() == 0) {
            return 0;
        } else if (datas.size() < 20) {
            return datas.size() + 1;
        } else {
            return datas.size() + 2;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TIME;
        } else if (position == datas.size() + 1) {
            return MORE;
        } else {
            return JOKES;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_copy_content:
                clipboardManager.setPrimaryClip(ClipData.newPlainText("joke", datas.get((Integer) v.getTag() - 1).getContent()));
                ToastUtil.showToast(context, "已复制");
                Log.e("wocao", "onClick: " + clipboardManager.getPrimaryClip());
                break;
            case R.id.btn_share_joke:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "分享欢乐");
                intent.putExtra(Intent.EXTRA_TEXT, datas.get((Integer) v.getTag() - 1).getContent());
                context.startActivity(Intent.createChooser(intent, "分享欢乐"));
                break;
            case R.id.btn_like_joke:

                Observable.just(myDao.queryExists(datas.get((Integer) v.getTag() - 1).getHashId()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aBoolean -> {
                            if (!aBoolean) {
                                Observable.just(myDao.addDate(System.currentTimeMillis()
                                        , datas.get((Integer) v.getTag() - 1).getContent()
                                        , datas.get((Integer) v.getTag() - 1).getHashId()
                                        , datas.get((Integer) v.getTag() - 1).getUnixtime()
                                        , datas.get((Integer) v.getTag() - 1).getUpdatetime()
                                        , ""
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(aLong -> {
                                            if (aLong != -1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_black_24dp);
                                                ToastUtil.showToast(context, "已收藏");
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEFAV, ""));
                                            }
                                        });
                            } else {
                                Observable.just(myDao.deleteDate(datas.get((Integer) v.getTag() - 1).getHashId()
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(integer -> {

                                            if (integer == 1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_border_black_24dp);
                                                ToastUtil.showToast(context, "已取消收藏");
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEFAV, ""));
                                            }

                                        });
                            }
                        });

        }
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        if (holder instanceof MoreHolder) {
            if (!isLoadingMore) {
                Log.e("wocao", "onViewAttachedToWindow: send event");
                RxBus.getDefault().post(new UserEvent(Constant.JOKELOADMORE, ""));
                isLoadingMore = true;
            }
        }

    }

    class JokesHolder extends RecyclerView.ViewHolder {
        TextView    joke_content;
        TextView    update_time;
        ImageButton btn_copy_content;
        ImageButton btn_share_joke;
        ImageButton btn_like_joke;

        public JokesHolder(View itemView) {
            super(itemView);
            joke_content = (TextView) itemView.findViewById(R.id.joke_content);
            update_time = (TextView) itemView.findViewById(R.id.update_time);
            btn_copy_content = (ImageButton) itemView.findViewById(R.id.btn_copy_content);
            btn_share_joke = (ImageButton) itemView.findViewById(R.id.btn_share_joke);
            btn_like_joke = (ImageButton) itemView.findViewById(R.id.btn_like_joke);
        }
    }


    //    加载更多
    class MoreHolder extends RecyclerView.ViewHolder {
        public MoreHolder(View itemView) {
            super(itemView);
        }
    }

    //    提示加载时间
    class TimeHodler extends RecyclerView.ViewHolder {
        public TimeHodler(View itemView) {
            super(itemView);
            itemView.setOnClickListener(v -> context.startActivity(new Intent(context, HiddenActivity.class)));
        }
    }
}
